<template>
  <div class="level-setting-container">
    <!-- 页面头部区域 -->
    <div class="level-header">
      <div class="header-content">
        <div class="ancient-title">职位等级设置</div>
        <div class="header-subtitle">阴曹地府 · 仙官等级体系管理</div>
      </div>
      <div class="header-decoration">
        <div class="decoration-line"></div>
        <div class="decoration-symbol">⬆️</div>
        <div class="decoration-line"></div>
      </div>
    </div>

    <!-- 路由信息显示 -->
    <div class="route-info">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/management">
            <ApartmentOutlined />
            机构管理
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <router-link to="/management/official-position">
            <CrownOutlined />
            仙官职位管理
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <RiseOutlined />
          {{ $route.meta.title }}
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <!-- 功能选项卡 -->
    <div class="tabs-section">
      <a-tabs v-model:activeKey="activeTab" type="card" @change="handleTabChange">
        <a-tab-pane key="levels" tab="等级管理">
          <template #tab>
            <span>
              <RiseOutlined />
              等级管理
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="promotion" tab="晋升流程">
          <template #tab>
            <span>
              <ArrowUpOutlined />
              晋升流程
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="salary" tab="薪资体系">
          <template #tab>
            <span>
              <DollarOutlined />
              薪资体系
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="assessment" tab="考核标准">
          <template #tab>
            <span>
              <CheckCircleOutlined />
              考核标准
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="statistics" tab="统计分析">
          <template #tab>
            <span>
              <LineChartOutlined />
              统计分析
            </span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 等级管理内容 -->
    <div v-show="activeTab === 'levels'">
      <!-- 操作区域 -->
      <div class="action-section">
        <a-row justify="space-between" align="middle">
          <a-col>
            <h3 class="section-title">
              <RiseOutlined class="section-icon" />
              等级体系管理
            </h3>
          </a-col>
          <a-col>
            <a-space>
              <a-button type="primary" @click="showAddLevelModal">
                <PlusOutlined />
                新增等级
              </a-button>
              <a-button @click="showImportModal">
                <ImportOutlined />
                批量导入
              </a-button>
              <a-button @click="exportLevels">
                <ExportOutlined />
                导出等级
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>

      <!-- 等级列表 -->
      <div class="level-list-section">
        <a-card title="职位等级列表" :bordered="false">
          <template #extra>
            <a-space>
              <a-select v-model:value="filterDepartment" placeholder="选择部门" style="width: 150px" allow-clear>
                <a-select-option value="all">全部部门</a-select-option>
                <a-select-option v-for="dept in departments" :key="dept.id" :value="dept.id">
                  {{ dept.name }}
                </a-select-option>
              </a-select>
              <a-input-search v-model:value="searchText" placeholder="搜索等级名称" style="width: 200px" @search="handleSearch" />
            </a-space>
          </template>

          <a-table :columns="levelColumns" :data-source="filteredLevels" :pagination="pagination" :loading="loading" row-key="id">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'level'">
                <a-tag :color="getLevelColor(record.level)"> 第{{ record.level }}级 </a-tag>
              </template>
              <template v-else-if="column.key === 'weight'">
                <a-progress :percent="record.weight" size="small" :show-info="false" />
                <span style="margin-left: 8px">{{ record.weight }}</span>
              </template>
              <template v-else-if="column.key === 'salary'">
                <span class="salary-range">{{ record.salaryRange }}</span>
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="record.status === 'active' ? 'green' : 'red'">
                  {{ record.status === 'active' ? '启用' : '禁用' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button type="link" size="small" @click="editLevel(record)">
                    <EditOutlined />
                    编辑
                  </a-button>
                  <a-button type="link" size="small" @click="viewLevelDetail(record)">
                    <EyeOutlined />
                    详情
                  </a-button>
                  <a-button type="link" size="small" @click="manageLevelAssessment(record)">
                    <CheckCircleOutlined />
                    考核
                  </a-button>
                  <a-popconfirm title="确定要删除这个等级吗？" @confirm="deleteLevel(record.id)" ok-text="确定" cancel-text="取消">
                    <a-button type="link" size="small" danger>
                      <DeleteOutlined />
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </div>
    </div>

    <!-- 晋升流程内容 -->
    <div v-show="activeTab === 'promotion'">
      <div class="promotion-section">
        <a-card title="晋升流程管理" :bordered="false">
          <template #extra>
            <a-button type="primary" @click="showAddPromotionModal">
              <PlusOutlined />
              新增晋升流程
            </a-button>
          </template>

          <a-row :gutter="24">
            <a-col :span="16">
              <div class="promotion-flow-chart">
                <h4>晋升流程图</h4>
                <div class="flow-steps">
                  <div v-for="(step, index) in promotionSteps" :key="step.id" class="step-item">
                    <div class="step-icon">
                      <component :is="step.icon" />
                    </div>
                    <div class="step-content">
                      <h5>{{ step.title }}</h5>
                      <p>{{ step.description }}</p>
                      <a-tag color="blue">{{ step.duration }}</a-tag>
                    </div>
                    <div v-if="index < promotionSteps.length - 1" class="step-arrow">
                      <ArrowRightOutlined />
                    </div>
                  </div>
                </div>
              </div>

              <div class="promotion-applications">
                <h4>晋升申请列表</h4>
                <a-table :columns="promotionColumns" :data-source="promotionApplications" :pagination="{ pageSize: 5 }" size="small">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'status'">
                      <a-tag :color="getPromotionStatusColor(record.status)">
                        {{ getPromotionStatusText(record.status) }}
                      </a-tag>
                    </template>
                    <template v-else-if="column.key === 'action'">
                      <a-space>
                        <a-button type="link" size="small" @click="viewPromotionDetail(record)">查看</a-button>
                        <a-button type="link" size="small" @click="processPromotion(record)">处理</a-button>
                      </a-space>
                    </template>
                  </template>
                </a-table>
              </div>
            </a-col>

            <a-col :span="8">
              <div class="promotion-stats">
                <h4>晋升统计</h4>
                <div class="stats-cards">
                  <div class="stat-card">
                    <div class="stat-number">{{ promotionStats.totalApplications }}</div>
                    <div class="stat-label">总申请数</div>
                  </div>
                  <div class="stat-card">
                    <div class="stat-number">{{ promotionStats.approvedCount }}</div>
                    <div class="stat-label">已通过</div>
                  </div>
                  <div class="stat-card">
                    <div class="stat-number">{{ promotionStats.pendingCount }}</div>
                    <div class="stat-label">待审批</div>
                  </div>
                  <div class="stat-card">
                    <div class="stat-number">{{ promotionStats.rejectedCount }}</div>
                    <div class="stat-label">已拒绝</div>
                  </div>
                </div>
              </div>

              <div class="promotion-rules">
                <h4>晋升规则</h4>
                <div class="rules-list">
                  <div v-for="rule in promotionRules" :key="rule.id" class="rule-item">
                    <div class="rule-title">{{ rule.title }}</div>
                    <div class="rule-content">{{ rule.content }}</div>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-card>
      </div>
    </div>

    <!-- 薪资体系内容 -->
    <div v-show="activeTab === 'salary'">
      <div class="salary-section">
        <a-card title="薪资体系管理" :bordered="false">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showSalaryConfigModal">
                <SettingOutlined />
                薪资配置
              </a-button>
              <a-button @click="exportSalaryData">
                <ExportOutlined />
                导出薪资
              </a-button>
            </a-space>
          </template>

          <a-row :gutter="24">
            <a-col :span="16">
              <div class="salary-chart">
                <h4>薪资等级分布</h4>
                <div id="salaryChart" class="chart-container"></div>
              </div>

              <div class="salary-table">
                <h4>等级薪资明细</h4>
                <a-table :columns="salaryColumns" :data-source="salaryData" :pagination="false" size="small">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'level'">
                      <a-tag :color="getLevelColor(record.level)">第{{ record.level }}级</a-tag>
                    </template>
                    <template v-else-if="column.key === 'baseSalary'">
                      <span class="salary-amount">{{ record.baseSalary.toLocaleString() }}</span>
                    </template>
                    <template v-else-if="column.key === 'allowance'">
                      <span class="salary-amount">{{ record.allowance.toLocaleString() }}</span>
                    </template>
                    <template v-else-if="column.key === 'bonus'">
                      <span class="salary-amount">{{ record.bonus.toLocaleString() }}</span>
                    </template>
                    <template v-else-if="column.key === 'total'">
                      <span class="salary-total">{{ record.total.toLocaleString() }}</span>
                    </template>
                    <template v-else-if="column.key === 'action'">
                      <a-button type="link" size="small" @click="editSalary(record)">
                        <EditOutlined />
                        调整
                      </a-button>
                    </template>
                  </template>
                </a-table>
              </div>
            </a-col>

            <a-col :span="8">
              <div class="salary-calculator">
                <h4>薪资计算器</h4>
                <a-form layout="vertical">
                  <a-form-item label="选择等级">
                    <a-select v-model:value="calculatorForm.level" placeholder="请选择等级">
                      <a-select-option v-for="level in levels" :key="level.id" :value="level.level"> 第{{ level.level }}级 - {{ level.name }} </a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="工龄（年）">
                    <a-input-number v-model:value="calculatorForm.workYears" :min="0" :max="50" style="width: 100%" />
                  </a-form-item>
                  <a-form-item label="绩效系数">
                    <a-input-number v-model:value="calculatorForm.performanceRatio" :min="0.5" :max="2.0" :step="0.1" style="width: 100%" />
                  </a-form-item>
                  <a-form-item>
                    <a-button type="primary" @click="calculateSalary" block>计算薪资</a-button>
                  </a-form-item>
                </a-form>

                <div v-if="calculatedSalary" class="salary-result">
                  <h5>计算结果</h5>
                  <div class="result-item">
                    <span>基本薪资：</span>
                    <span class="amount">{{ calculatedSalary.base.toLocaleString() }}</span>
                  </div>
                  <div class="result-item">
                    <span>工龄津贴：</span>
                    <span class="amount">{{ calculatedSalary.seniority.toLocaleString() }}</span>
                  </div>
                  <div class="result-item">
                    <span>绩效奖金：</span>
                    <span class="amount">{{ calculatedSalary.performance.toLocaleString() }}</span>
                  </div>
                  <div class="result-total">
                    <span>总计：</span>
                    <span class="total-amount">{{ calculatedSalary.total.toLocaleString() }}</span>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-card>
      </div>
    </div>

    <!-- 考核标准内容 -->
    <div v-show="activeTab === 'assessment'">
      <div class="assessment-section">
        <a-card title="考核标准管理" :bordered="false">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showAddAssessmentModal">
                <PlusOutlined />
                新增考核标准
              </a-button>
              <a-button @click="exportAssessmentData">
                <ExportOutlined />
                导出标准
              </a-button>
            </a-space>
          </template>

          <a-row :gutter="24">
            <a-col :span="16">
              <div class="assessment-standards">
                <h4>考核标准列表</h4>
                <a-table :columns="assessmentColumns" :data-source="assessmentStandards" :pagination="{ pageSize: 8 }" size="small">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'level'">
                      <a-tag :color="getLevelColor(record.level)">第{{ record.level }}级</a-tag>
                    </template>
                    <template v-else-if="column.key === 'weight'">
                      <a-progress :percent="record.weight" size="small" :show-info="false" />
                      <span style="margin-left: 8px">{{ record.weight }}%</span>
                    </template>
                    <template v-else-if="column.key === 'status'">
                      <a-tag :color="record.status === 'active' ? 'green' : 'red'">
                        {{ record.status === 'active' ? '启用' : '禁用' }}
                      </a-tag>
                    </template>
                    <template v-else-if="column.key === 'action'">
                      <a-space>
                        <a-button type="link" size="small" @click="editAssessment(record)">编辑</a-button>
                        <a-button type="link" size="small" @click="viewAssessmentDetail(record)">详情</a-button>
                        <a-popconfirm title="确定删除？" @confirm="deleteAssessment(record.id)">
                          <a-button type="link" size="small" danger>删除</a-button>
                        </a-popconfirm>
                      </a-space>
                    </template>
                  </template>
                </a-table>
              </div>
            </a-col>

            <a-col :span="8">
              <div class="assessment-config">
                <h4>考核配置</h4>
                <a-form layout="vertical">
                  <a-form-item label="考核周期">
                    <a-select v-model:value="assessmentConfig.cycle" placeholder="选择考核周期">
                      <a-select-option value="monthly">月度考核</a-select-option>
                      <a-select-option value="quarterly">季度考核</a-select-option>
                      <a-select-option value="annual">年度考核</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="考核方式">
                    <a-checkbox-group v-model:value="assessmentConfig.methods">
                      <a-checkbox value="self">自评</a-checkbox>
                      <a-checkbox value="peer">同级互评</a-checkbox>
                      <a-checkbox value="superior">上级评价</a-checkbox>
                      <a-checkbox value="subordinate">下级评价</a-checkbox>
                    </a-checkbox-group>
                  </a-form-item>
                  <a-form-item label="通过分数">
                    <a-input-number v-model:value="assessmentConfig.passingScore" :min="0" :max="100" style="width: 100%" />
                  </a-form-item>
                </a-form>
              </div>

              <div class="assessment-template">
                <h4>考核模板</h4>
                <div class="template-list">
                  <div v-for="template in assessmentTemplates" :key="template.id" class="template-item">
                    <div class="template-name">{{ template.name }}</div>
                    <div class="template-description">{{ template.description }}</div>
                    <div class="template-actions">
                      <a-button type="link" size="small" @click="applyTemplate(template)">应用</a-button>
                    </div>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-card>
      </div>
    </div>

    <!-- 统计分析内容 -->
    <div v-show="activeTab === 'statistics'">
      <div class="statistics-section">
        <a-card title="等级统计分析" :bordered="false">
          <template #extra>
            <a-space>
              <a-range-picker v-model:value="statisticsDateRange" @change="updateStatistics" />
              <a-button @click="refreshCharts" type="primary">
                <LineChartOutlined />
                刷新图表
              </a-button>
              <a-button @click="exportStatistics">
                <ExportOutlined />
                导出报告
              </a-button>
            </a-space>
          </template>

          <a-row :gutter="24">
            <a-col :span="12">
              <div class="level-distribution">
                <h4>等级分布统计</h4>
                <div class="distribution-chart">
                  <div id="levelDistributionChart" style="width: 100%; height: 100%"></div>
                </div>
              </div>
            </a-col>

            <a-col :span="12">
              <div class="promotion-trend">
                <h4>晋升趋势分析</h4>
                <div class="trend-chart">
                  <div id="promotionTrendChart" style="width: 100%; height: 100%"></div>
                </div>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="24" style="margin-top: 24px">
            <a-col :span="8">
              <div class="department-stats">
                <h4>部门等级统计</h4>
                <div class="stats-list">
                  <div v-for="dept in departmentStats" :key="dept.id" class="dept-stat-item">
                    <div class="dept-name">{{ dept.name }}</div>
                    <div class="dept-levels">
                      <a-tag v-for="level in dept.levels" :key="level.level" :color="getLevelColor(level.level)" size="small"> {{ level.level }}级({{ level.count }}) </a-tag>
                    </div>
                  </div>
                </div>
              </div>
            </a-col>

            <a-col :span="8">
              <div class="performance-stats">
                <h4>绩效统计</h4>
                <div class="performance-list">
                  <div v-for="perf in performanceStats" :key="perf.level" class="perf-item">
                    <div class="perf-level">第{{ perf.level }}级</div>
                    <div class="perf-score">
                      <a-progress :percent="perf.averageScore" :show-info="false" size="small" />
                      <span style="margin-left: 8px">{{ perf.averageScore }}分</span>
                    </div>
                  </div>
                </div>
              </div>
            </a-col>

            <a-col :span="8">
              <div class="retention-stats">
                <h4>留任统计</h4>
                <div class="retention-list">
                  <div v-for="retention in retentionStats" :key="retention.level" class="retention-item">
                    <div class="retention-level">第{{ retention.level }}级</div>
                    <div class="retention-rate">
                      <a-progress :percent="retention.rate" :show-info="false" size="small" />
                      <span style="margin-left: 8px">{{ retention.rate }}%</span>
                    </div>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-card>
      </div>
    </div>

    <!-- 新增/编辑等级弹窗 -->
    <a-modal v-model:open="levelModalVisible" :title="modalTitle" @ok="handleLevelSubmit" @cancel="handleLevelCancel" width="800px">
      <a-form ref="levelFormRef" :model="levelForm" :rules="levelRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="等级" name="level">
              <a-input-number v-model:value="levelForm.level" :min="1" :max="20" placeholder="请输入等级" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="等级权重" name="weight">
              <a-input-number v-model:value="levelForm.weight" :min="0" :max="100" placeholder="权重分数" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="等级名称" name="name">
              <a-input v-model:value="levelForm.name" placeholder="请输入等级名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属部门" name="department">
              <a-select v-model:value="levelForm.department" placeholder="选择所属部门">
                <a-select-option v-for="dept in departments" :key="dept.id" :value="dept.id">
                  {{ dept.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="基础薪资" name="baseSalary">
              <a-input-number v-model:value="levelForm.baseSalary" :min="0" placeholder="基础薪资" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="职务津贴" name="allowance">
              <a-input-number v-model:value="levelForm.allowance" :min="0" placeholder="职务津贴" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="晋升条件" name="promotionConditions">
          <a-textarea v-model:value="levelForm.promotionConditions" placeholder="描述晋升到此等级的条件" :rows="3" />
        </a-form-item>

        <a-form-item label="工作职责" name="responsibilities">
          <a-textarea v-model:value="levelForm.responsibilities" placeholder="描述此等级的工作职责" :rows="3" />
        </a-form-item>

        <a-form-item label="等级权限" name="permissions">
          <a-checkbox-group v-model:value="levelForm.permissions">
            <a-row>
              <a-col :span="8" v-for="permission in allPermissions" :key="permission.id">
                <a-checkbox :value="permission.id">{{ permission.name }}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="levelForm.status">
            <a-radio value="active">启用</a-radio>
            <a-radio value="inactive">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 等级详情弹窗 -->
    <a-modal v-model:open="detailModalVisible" title="等级详情" :footer="null" width="900px">
      <div v-if="selectedLevel">
        <a-descriptions title="基本信息" :column="2" bordered>
          <a-descriptions-item label="等级">
            <a-tag :color="getLevelColor(selectedLevel.level)"> 第{{ selectedLevel.level }}级 </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="等级名称">{{ selectedLevel.name }}</a-descriptions-item>
          <a-descriptions-item label="所属部门">{{ getDepartmentName(selectedLevel.department) }}</a-descriptions-item>
          <a-descriptions-item label="等级权重">
            <a-progress :percent="selectedLevel.weight" size="small" />
          </a-descriptions-item>
          <a-descriptions-item label="基础薪资">{{ selectedLevel.baseSalary?.toLocaleString() || '未设置' }}</a-descriptions-item>
          <a-descriptions-item label="职务津贴">{{ selectedLevel.allowance?.toLocaleString() || '未设置' }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="selectedLevel.status === 'active' ? 'green' : 'red'">
              {{ selectedLevel.status === 'active' ? '启用' : '禁用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ selectedLevel.createTime }}</a-descriptions-item>
        </a-descriptions>

        <a-divider>晋升条件</a-divider>
        <p>{{ selectedLevel.promotionConditions }}</p>

        <a-divider>工作职责</a-divider>
        <p>{{ selectedLevel.responsibilities || '暂无职责描述' }}</p>

        <a-divider>等级权限</a-divider>
        <a-tag v-for="permissionId in selectedLevel.permissions" :key="permissionId" style="margin-bottom: 8px">
          {{ getPermissionName(permissionId) }}
        </a-tag>

        <a-divider>等级统计</a-divider>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-statistic title="当前人数" :value="selectedLevel.currentCount" />
          </a-col>
          <a-col :span="8">
            <a-statistic title="本月晋升" :value="selectedLevel.monthlyPromotions" />
          </a-col>
          <a-col :span="8">
            <a-statistic title="本月降级" :value="selectedLevel.monthlyDemotions" />
          </a-col>
        </a-row>
      </div>
    </a-modal>

    <!-- 批量导入弹窗 -->
    <a-modal v-model:open="importModalVisible" title="批量导入等级" @ok="handleImport" @cancel="handleImportCancel" width="600px">
      <a-upload-dragger v-model:fileList="importFileList" name="file" :multiple="false" :before-upload="beforeUpload" accept=".xlsx,.xls" @change="handleFileChange">
        <p class="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
        <p class="ant-upload-hint">支持Excel格式文件（.xlsx, .xls）</p>
      </a-upload-dragger>

      <div class="import-template">
        <a-divider>模板下载</a-divider>
        <a-button type="link" @click="downloadTemplate">
          <DownloadOutlined />
          下载导入模板
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  HomeOutlined,
  ApartmentOutlined,
  CrownOutlined,
  RiseOutlined,
  ArrowUpOutlined,
  DollarOutlined,
  CheckCircleOutlined,
  LineChartOutlined,
  PlusOutlined,
  ExportOutlined,
  ImportOutlined,
  EditOutlined,
  EyeOutlined,
  DeleteOutlined,
  SettingOutlined,
  ArrowRightOutlined,
  InboxOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const activeTab = ref('levels')
const loading = ref(false)
const searchText = ref('')
const filterDepartment = ref('')
const levelModalVisible = ref(false)
const detailModalVisible = ref(false)
const importModalVisible = ref(false)
const selectedLevel = ref(null)
const levelFormRef = ref()
const importFileList = ref([])
const statisticsDateRange = ref([])
let salaryChart = null
let levelChart = null
let trendChart = null

// 监听选项卡变化，确保图表在显示时能正确调整大小
watch(activeTab, (newVal) => {
  // 使用 nextTick 确保 DOM 元素已经渲染并可见
  if (newVal === 'salary') {
    nextTick(() => {
      salaryChart?.resize()
    })
  } else if (newVal === 'statistics') {
    nextTick(() => {
      levelChart?.resize()
      trendChart?.resize()
    })
  }
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const levelColumns = [
  { title: '等级', dataIndex: 'level', key: 'level', width: 80, sorter: true },
  { title: '等级名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '所属部门', dataIndex: 'department', key: 'department', width: 120, customRender: ({ text }) => getDepartmentName(text) },
  { title: '等级权重', dataIndex: 'weight', key: 'weight', width: 120, sorter: true },
  { title: '薪资范围', dataIndex: 'salaryRange', key: 'salary', width: 120 },
  { title: '当前人数', dataIndex: 'currentCount', key: 'currentCount', width: 100, sorter: true },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 120 },
  { title: '操作', key: 'action', width: 250, fixed: 'right' }
]

// 晋升流程列配置
const promotionColumns = [
  { title: '申请人', dataIndex: 'applicant', key: 'applicant', width: 100 },
  { title: '当前等级', dataIndex: 'currentLevel', key: 'currentLevel', width: 100 },
  { title: '目标等级', dataIndex: 'targetLevel', key: 'targetLevel', width: 100 },
  { title: '申请时间', dataIndex: 'applyTime', key: 'applyTime', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 120 }
]

// 薪资列配置
const salaryColumns = [
  { title: '等级', dataIndex: 'level', key: 'level', width: 80 },
  { title: '等级名称', dataIndex: 'levelName', key: 'levelName', width: 120 },
  { title: '基础薪资', dataIndex: 'baseSalary', key: 'baseSalary', width: 100 },
  { title: '职务津贴', dataIndex: 'allowance', key: 'allowance', width: 100 },
  { title: '绩效奖金', dataIndex: 'bonus', key: 'bonus', width: 100 },
  { title: '合计', dataIndex: 'total', key: 'total', width: 100 },
  { title: '操作', key: 'action', width: 80 }
]

// 考核标准列配置
const assessmentColumns = [
  { title: '等级', dataIndex: 'level', key: 'level', width: 80 },
  { title: '考核项目', dataIndex: 'name', key: 'name', width: 150 },
  { title: '权重', dataIndex: 'weight', key: 'weight', width: 100 },
  { title: '考核周期', dataIndex: 'cycle', key: 'cycle', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 150 }
]

// 部门数据
const departments = ref([
  { id: 'first_court', name: '第一殿秦广王府' },
  { id: 'second_court', name: '第二殿楚江王府' },
  { id: 'third_court', name: '第三殿宋帝王府' },
  { id: 'fourth_court', name: '第四殿五官王府' },
  { id: 'fifth_court', name: '第五殿阎罗王府' },
  { id: 'sixth_court', name: '第六殿卞城王府' },
  { id: 'seventh_court', name: '第七殿泰山王府' },
  { id: 'eighth_court', name: '第八殿都市王府' },
  { id: 'ninth_court', name: '第九殿平等王府' },
  { id: 'tenth_court', name: '第十殿转轮王府' }
])

// 权限数据
const allPermissions = ref([
  { id: 'view_archives', name: '查看档案' },
  { id: 'edit_archives', name: '编辑档案' },
  { id: 'manage_life_death', name: '生死管理' },
  { id: 'karma_judgment', name: '业力审判' },
  { id: 'reincarnation_control', name: '轮回控制' },
  { id: 'salvation_approval', name: '超度审批' },
  { id: 'system_admin', name: '系统管理' },
  { id: 'data_export', name: '数据导出' },
  { id: 'user_management', name: '用户管理' },
  { id: 'schedule_management', name: '排班管理' },
  { id: 'report_view', name: '报表查看' },
  { id: 'audit_log', name: '审计日志' }
])

// 等级数据
const levels = ref([
  {
    id: 1,
    level: 1,
    name: '见习仙官',
    department: 'first_court',
    weight: 10,
    baseSalary: 3000,
    allowance: 500,
    salaryRange: '3,000-3,500',
    currentCount: 156,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '新入职仙官，完成基础培训即可获得此等级',
    responsibilities: '负责基础档案录入、简单案件初审、日常事务处理',
    permissions: ['view_archives'],
    monthlyPromotions: 8,
    monthlyDemotions: 2
  },
  {
    id: 2,
    level: 2,
    name: '初级仙官',
    department: 'second_court',
    weight: 20,
    baseSalary: 4000,
    allowance: 800,
    salaryRange: '4,000-4,800',
    currentCount: 234,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '工作满6个月，无重大过失，完成相关考核',
    responsibilities: '负责一般案件审理、档案管理、协助上级处理复杂事务',
    permissions: ['view_archives', 'edit_archives'],
    monthlyPromotions: 12,
    monthlyDemotions: 1
  },
  {
    id: 3,
    level: 3,
    name: '中级仙官',
    department: 'third_court',
    weight: 35,
    baseSalary: 5500,
    allowance: 1200,
    salaryRange: '5,500-6,700',
    currentCount: 189,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '工作满2年，业绩优秀，通过专业技能考试',
    responsibilities: '负责复杂案件审理、业力评估、新人培训指导',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment'],
    monthlyPromotions: 6,
    monthlyDemotions: 0
  },
  {
    id: 4,
    level: 4,
    name: '高级仙官',
    department: 'fourth_court',
    weight: 50,
    baseSalary: 7000,
    allowance: 1800,
    salaryRange: '7,000-8,800',
    currentCount: 145,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '工作满5年，有突出贡献，获得上级推荐',
    responsibilities: '负责疑难案件处理、生死簿管理、跨部门协调',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment', 'manage_life_death'],
    monthlyPromotions: 3,
    monthlyDemotions: 0
  },
  {
    id: 5,
    level: 5,
    name: '主管仙官',
    department: 'fifth_court',
    weight: 65,
    baseSalary: 9000,
    allowance: 2500,
    salaryRange: '9,000-11,500',
    currentCount: 98,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '具备管理能力，有团队领导经验，通过管理考核',
    responsibilities: '负责部门管理、团队建设、重大决策参与',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment', 'manage_life_death', 'user_management'],
    monthlyPromotions: 2,
    monthlyDemotions: 0
  },
  {
    id: 6,
    level: 6,
    name: '督查仙官',
    department: 'sixth_court',
    weight: 78,
    baseSalary: 12000,
    allowance: 3000,
    salaryRange: '12,000-15,000',
    currentCount: 67,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '工作满10年，具备专业监督能力，无违纪记录',
    responsibilities: '负责监督检查、纪律审查、制度完善',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment', 'manage_life_death', 'user_management', 'audit_log'],
    monthlyPromotions: 1,
    monthlyDemotions: 0
  },
  {
    id: 7,
    level: 7,
    name: '判官',
    department: 'seventh_court',
    weight: 88,
    baseSalary: 15000,
    allowance: 4000,
    salaryRange: '15,000-19,000',
    currentCount: 45,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '德才兼备，具备独立审判能力，经阎王推荐',
    responsibilities: '负责重大案件审判、轮回安排、超度审批',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment', 'manage_life_death', 'reincarnation_control', 'salvation_approval'],
    monthlyPromotions: 1,
    monthlyDemotions: 0
  },
  {
    id: 8,
    level: 8,
    name: '副王',
    department: 'eighth_court',
    weight: 95,
    baseSalary: 20000,
    allowance: 5000,
    salaryRange: '20,000-25,000',
    currentCount: 23,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '资历深厚，能力卓越，经玉帝特批',
    responsibilities: '负责殿务管理、政策制定、对外协调',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment', 'manage_life_death', 'reincarnation_control', 'salvation_approval', 'system_admin'],
    monthlyPromotions: 0,
    monthlyDemotions: 0
  },
  {
    id: 9,
    level: 9,
    name: '阎王',
    department: 'ninth_court',
    weight: 100,
    baseSalary: 30000,
    allowance: 8000,
    salaryRange: '30,000-38,000',
    currentCount: 10,
    status: 'active',
    createTime: '2023-01-15',
    promotionConditions: '地府最高等级，需具备统领一方的能力和威望',
    responsibilities: '负责全殿统筹、重大决策、与天庭沟通',
    permissions: ['view_archives', 'edit_archives', 'karma_judgment', 'manage_life_death', 'reincarnation_control', 'salvation_approval', 'system_admin', 'data_export', 'report_view'],
    monthlyPromotions: 0,
    monthlyDemotions: 0
  }
])

// 晋升流程步骤
const promotionSteps = ref([
  {
    id: 1,
    icon: 'FileTextOutlined',
    title: '申请提交',
    description: '仙官提交晋升申请，填写相关材料',
    duration: '1-2天'
  },
  {
    id: 2,
    icon: 'AuditOutlined',
    title: '初审',
    description: '直属上级进行初步审核',
    duration: '3-5天'
  },
  {
    id: 3,
    icon: 'CheckCircleOutlined',
    title: '考核评估',
    description: '进行专业技能和综合素质考核',
    duration: '7-10天'
  },
  {
    id: 4,
    icon: 'CrownOutlined',
    title: '最终审批',
    description: '阎王或更高级别进行最终审批',
    duration: '5-7天'
  },
  {
    id: 5,
    icon: 'CheckOutlined',
    title: '晋升确认',
    description: '确认晋升结果并更新档案',
    duration: '1-2天'
  }
])

// 晋升申请数据
const promotionApplications = ref([
  {
    id: 1,
    applicant: '张三',
    currentLevel: 2,
    targetLevel: 3,
    applyTime: '2024-01-15',
    status: 'pending'
  },
  {
    id: 2,
    applicant: '李四',
    currentLevel: 3,
    targetLevel: 4,
    applyTime: '2024-01-20',
    status: 'approved'
  },
  {
    id: 3,
    applicant: '王五',
    currentLevel: 1,
    targetLevel: 2,
    applyTime: '2024-01-25',
    status: 'rejected'
  }
])

// 晋升统计
const promotionStats = reactive({
  totalApplications: 156,
  approvedCount: 89,
  pendingCount: 45,
  rejectedCount: 22
})

// 晋升规则
const promotionRules = ref([
  {
    id: 1,
    title: '工作年限要求',
    content: '必须在当前等级工作满规定年限方可申请晋升'
  },
  {
    id: 2,
    title: '考核成绩要求',
    content: '最近两次考核成绩必须达到优秀或以上'
  },
  {
    id: 3,
    title: '无违纪记录',
    content: '申请前一年内不得有重大违纪行为记录'
  }
])

// 薪资数据
const salaryData = ref([
  { level: 1, levelName: '见习仙官', baseSalary: 3000, allowance: 500, bonus: 300, total: 3800 },
  { level: 2, levelName: '初级仙官', baseSalary: 4000, allowance: 800, bonus: 500, total: 5300 },
  { level: 3, levelName: '中级仙官', baseSalary: 5500, allowance: 1200, bonus: 800, total: 7500 },
  { level: 4, levelName: '高级仙官', baseSalary: 7000, allowance: 1800, bonus: 1200, total: 10000 },
  { level: 5, levelName: '主管仙官', baseSalary: 9000, allowance: 2500, bonus: 1800, total: 13300 },
  { level: 6, levelName: '督查仙官', baseSalary: 12000, allowance: 3000, bonus: 2500, total: 17500 },
  { level: 7, levelName: '判官', baseSalary: 15000, allowance: 4000, bonus: 3500, total: 22500 },
  { level: 8, levelName: '副王', baseSalary: 20000, allowance: 5000, bonus: 5000, total: 30000 },
  { level: 9, levelName: '阎王', baseSalary: 30000, allowance: 8000, bonus: 10000, total: 48000 }
])

// 薪资计算器表单
const calculatorForm = reactive({
  level: null,
  workYears: 0,
  performanceRatio: 1.0
})

// 计算结果
const calculatedSalary = ref(null)

// 考核标准数据
const assessmentStandards = ref([
  { id: 1, level: 1, name: '基础业务能力', weight: 40, cycle: 'monthly', status: 'active' },
  { id: 2, level: 1, name: '工作态度', weight: 30, cycle: 'monthly', status: 'active' },
  { id: 3, level: 1, name: '学习能力', weight: 30, cycle: 'monthly', status: 'active' },
  { id: 4, level: 2, name: '专业技能', weight: 50, cycle: 'quarterly', status: 'active' },
  { id: 5, level: 2, name: '团队协作', weight: 25, cycle: 'quarterly', status: 'active' },
  { id: 6, level: 2, name: '创新能力', weight: 25, cycle: 'quarterly', status: 'active' }
])

// 考核配置
const assessmentConfig = reactive({
  cycle: 'monthly',
  methods: ['self', 'superior'],
  passingScore: 80
})

// 考核模板
const assessmentTemplates = ref([
  { id: 1, name: '基础岗位考核', description: '适用于1-3级仙官的基础考核模板' },
  { id: 2, name: '管理岗位考核', description: '适用于4-6级仙官的管理考核模板' },
  { id: 3, name: '高级岗位考核', description: '适用于7-9级仙官的高级考核模板' }
])

// 统计数据
const departmentStats = ref([
  {
    id: 'first_court',
    name: '第一殿秦广王府',
    levels: [
      { level: 1, count: 25 },
      { level: 2, count: 30 },
      { level: 3, count: 20 }
    ]
  },
  {
    id: 'second_court',
    name: '第二殿楚江王府',
    levels: [
      { level: 2, count: 28 },
      { level: 3, count: 25 },
      { level: 4, count: 15 }
    ]
  }
])

const performanceStats = ref([
  { level: 1, averageScore: 78 },
  { level: 2, averageScore: 82 },
  { level: 3, averageScore: 85 },
  { level: 4, averageScore: 88 },
  { level: 5, averageScore: 92 }
])

const retentionStats = ref([
  { level: 1, rate: 85 },
  { level: 2, rate: 92 },
  { level: 3, rate: 95 },
  { level: 4, rate: 98 },
  { level: 5, rate: 99 }
])

// 表单数据
const levelForm = reactive({
  level: null,
  name: '',
  department: '',
  weight: null,
  baseSalary: null,
  allowance: null,
  promotionConditions: '',
  responsibilities: '',
  permissions: [],
  status: 'active'
})

// 表单验证规则
const levelRules = {
  level: [{ required: true, message: '请输入等级', trigger: 'blur' }],
  name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  department: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  weight: [{ required: true, message: '请输入等级权重', trigger: 'blur' }],
  baseSalary: [{ required: true, message: '请输入基础薪资', trigger: 'blur' }],
  allowance: [{ required: true, message: '请输入职务津贴', trigger: 'blur' }],
  promotionConditions: [{ required: true, message: '请输入晋升条件', trigger: 'blur' }],
  responsibilities: [{ required: true, message: '请输入工作职责', trigger: 'blur' }]
}

// 计算属性
const modalTitle = computed(() => {
  return levelForm.id ? '编辑等级' : '新增等级'
})

const filteredLevels = computed(() => {
  let result = levels.value

  if (filterDepartment.value && filterDepartment.value !== 'all') {
    result = result.filter((level) => level.department === filterDepartment.value)
  }

  if (searchText.value) {
    result = result.filter((level) => level.name.toLowerCase().includes(searchText.value.toLowerCase()))
  }

  pagination.total = result.length
  return result
})

// 方法
const handleTabChange = (key) => {
  initCharts()

  activeTab.value = key
}

const getLevelColor = (level) => {
  const colors = ['#f50', '#2db7f5', '#87d068', '#108ee9', '#f56a00', '#eb2f96', '#722ed1', '#fa541c', '#1890ff']
  return colors[level - 1] || '#999'
}

const getDepartmentName = (departmentId) => {
  const dept = departments.value.find((d) => d.id === departmentId)
  return dept ? dept.name : departmentId
}

const getPermissionName = (permissionId) => {
  const permission = allPermissions.value.find((p) => p.id === permissionId)
  return permission ? permission.name : permissionId
}

const getPromotionStatusColor = (status) => {
  const colors = {
    pending: 'orange',
    approved: 'green',
    rejected: 'red',
    processing: 'blue'
  }
  return colors[status] || 'default'
}

const getPromotionStatusText = (status) => {
  const texts = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝',
    processing: '处理中'
  }
  return texts[status] || status
}

const showAddLevelModal = () => {
  Object.assign(levelForm, {
    id: null,
    level: null,
    name: '',
    department: '',
    weight: null,
    baseSalary: null,
    allowance: null,
    promotionConditions: '',
    responsibilities: '',
    permissions: [],
    status: 'active'
  })
  levelModalVisible.value = true
}

const editLevel = (record) => {
  Object.assign(levelForm, { ...record })
  levelModalVisible.value = true
}

const handleLevelSubmit = async () => {
  try {
    await levelFormRef.value.validate()

    if (levelForm.id) {
      // 编辑逻辑
      const index = levels.value.findIndex((l) => l.id === levelForm.id)
      if (index !== -1) {
        levels.value[index] = {
          ...levelForm,
          salaryRange: `${levelForm.baseSalary?.toLocaleString()}-${(levelForm.baseSalary + levelForm.allowance)?.toLocaleString()}`
        }
      }
      message.success('等级更新成功')
    } else {
      // 新增逻辑
      const newLevel = {
        ...levelForm,
        id: Date.now(),
        currentCount: 0,
        createTime: new Date().toISOString().split('T')[0],
        salaryRange: `${levelForm.baseSalary?.toLocaleString()}-${(levelForm.baseSalary + levelForm.allowance)?.toLocaleString()}`,
        monthlyPromotions: 0,
        monthlyDemotions: 0
      }
      levels.value.push(newLevel)
      message.success('等级创建成功')
    }

    levelModalVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleLevelCancel = () => {
  levelModalVisible.value = false
}

const viewLevelDetail = (record) => {
  selectedLevel.value = record
  detailModalVisible.value = true
}

const deleteLevel = (levelId) => {
  const index = levels.value.findIndex((l) => l.id === levelId)
  if (index !== -1) {
    levels.value.splice(index, 1)
    message.success('等级删除成功')
  }
}

const manageLevelAssessment = (record) => {
  message.info(`等级考核管理功能开发中... 等级：${record.name}`)
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const exportLevels = () => {
  message.info('等级数据导出功能开发中...')
}

const showImportModal = () => {
  importModalVisible.value = true
}

const handleImport = () => {
  message.info('批量导入功能开发中...')
  importModalVisible.value = false
}

const handleImportCancel = () => {
  importModalVisible.value = false
  importFileList.value = []
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    message.error('只能上传Excel文件!')
  }
  return isExcel
}

const handleFileChange = (info) => {
  if (info.file.status === 'done') {
    message.success('文件上传成功')
  } else if (info.file.status === 'error') {
    message.error('文件上传失败')
  }
}

const downloadTemplate = () => {
  message.info('模板下载功能开发中...')
}

const showAddPromotionModal = () => {
  message.info('新增晋升流程功能开发中...')
}

const viewPromotionDetail = (record) => {
  message.info(`查看晋升详情: ${record.applicant}`)
}

const processPromotion = (record) => {
  message.info(`处理晋升申请: ${record.applicant}`)
}

const showSalaryConfigModal = () => {
  message.info('薪资配置功能开发中...')
}

const exportSalaryData = () => {
  message.info('薪资数据导出功能开发中...')
}

const editSalary = (record) => {
  message.info(`调整薪资: ${record.levelName}`)
}

const calculateSalary = () => {
  if (!calculatorForm.level) {
    message.warning('请选择等级')
    return
  }

  const levelData = levels.value.find((l) => l.level === calculatorForm.level)
  if (!levelData) {
    message.error('等级数据不存在')
    return
  }

  const base = levelData.baseSalary
  const seniority = calculatorForm.workYears * 100
  const performance = base * (calculatorForm.performanceRatio - 1)
  const total = base + levelData.allowance + seniority + performance

  calculatedSalary.value = {
    base,
    seniority,
    performance,
    total
  }
}

const showAddAssessmentModal = () => {
  message.info('新增考核标准功能开发中...')
}

const exportAssessmentData = () => {
  message.info('考核标准导出功能开发中...')
}

const editAssessment = (record) => {
  message.info(`编辑考核标准: ${record.name}`)
}

const viewAssessmentDetail = (record) => {
  message.info(`查看考核详情: ${record.name}`)
}

const deleteAssessment = (id) => {
  const index = assessmentStandards.value.findIndex((a) => a.id === id)
  if (index !== -1) {
    assessmentStandards.value.splice(index, 1)
    message.success('考核标准删除成功')
  }
}

const applyTemplate = (template) => {
  message.info(`应用模板: ${template.name}`)
}

const updateStatistics = () => {
  message.info('统计数据更新中...')
}

const exportStatistics = () => {
  message.info('统计报告导出功能开发中...')
}

const refreshCharts = () => {
  // 清除旧图表
  try {
    if (salaryChart) {
      salaryChart.dispose()
      salaryChart = null
    }
    if (levelChart) {
      levelChart.dispose()
      levelChart = null
    }
    if (trendChart) {
      trendChart.dispose()
      trendChart = null
    }
  } catch (e) {
    console.warn('清理图表失败:', e)
  }

  // 显示加载提示
  const loadingMessage = message.loading('正在刷新图表...', 0)

  // 延迟初始化图表
  setTimeout(() => {
    initCharts()

    // 关闭加载提示并显示成功消息
    setTimeout(() => {
      loadingMessage()
      message.success('图表刷新成功！', 1.5)
    }, 500)
  }, 100)
}

// 图表初始化函数
const initCharts = () => {
  // 添加延迟确保DOM完全渲染
  setTimeout(() => {
    nextTick(() => {
      try {
        // 薪资图表
        const salaryChartDom = document.getElementById('salaryChart')
        if (salaryChartDom && salaryChartDom.offsetWidth > 0 && salaryChartDom.offsetHeight > 0) {
          // 如果图表已存在，先销毁
          if (salaryChart) {
            try {
              salaryChart.dispose()
            } catch (e) {
              console.warn('销毁薪资图表失败:', e)
            }
            salaryChart = null
          }

          salaryChart = echarts.init(salaryChartDom)
          const salaryOption = {
            title: {
              text: '薪资等级分布',
              left: 'center',
              top: 10,
              textStyle: {
                fontSize: 18,
                fontWeight: 'bold',
                color: '#fff',
                textShadow: '2px 2px 4px rgba(0,0,0,0.1)'
              }
            },
            tooltip: {
              trigger: 'axis',
              backgroundColor: 'rgba(0,0,0,0.9)',
              borderColor: '#333',
              borderWidth: 1,
              padding: [10, 15],
              textStyle: {
                color: '#fff',
                fontSize: 12
              },
              formatter: function (params) {
                let result = `${params[0].name}<br/>`
                params.forEach((param) => {
                  let marker = `<span style="display:inline-block;margin-right:4px;border-radius:50%;width:10px;height:10px;background-color:${param.color};"></span>`
                  result += `${marker}${param.seriesName}: ${param.value.toLocaleString()} 功德<br/>`
                })
                return result
              }
            },
            legend: {
              data: ['基础薪资', '职务津贴', '绩效奖金', '总薪资'],
              top: 40,
              textStyle: {
                color: '#fff',
                fontSize: 12
              },
              itemWidth: 15,
              itemHeight: 15,
              itemGap: 25
            },
            grid: {
              left: '8%',
              right: '8%',
              bottom: '15%',
              top: '15%'
            },
            xAxis: {
              type: 'category',
              data: ['见习仙官', '初级仙官', '中级仙官', '高级仙官', '主管仙官', '督查仙官', '判官', '副王', '阎王'],
              axisLabel: {
                color: '#fff',
                fontSize: 12,
                rotate: 45,
                interval: 0
              },
              axisLine: {
                lineStyle: {
                  color: '#fff'
                }
              },
              axisTick: {
                show: false
              }
            },
            yAxis: {
              type: 'value',
              name: '薪资（功德）',
              nameTextStyle: {
                color: '#fff',
                fontSize: 12,
                padding: [0, 0, 0, 40]
              },
              axisLabel: {
                color: '#4A5568',
                fontSize: 12,
                formatter: (value) => value.toLocaleString()
              },
              axisLine: {
                show: false
              },
              splitLine: {
                lineStyle: {
                  color: '#fff',
                  type: 'dashed'
                }
              }
            },
            series: [
              {
                name: '基础薪资',
                type: 'bar',
                stack: 'salary',
                data: [3000, 4000, 5500, 7000, 9000, 12000, 15000, 20000, 30000],
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#4299E1' },
                    { offset: 1, color: '#2B6CB0' }
                  ]),
                  borderRadius: [4, 4, 0, 0]
                },
                emphasis: {
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#63B3ED' },
                      { offset: 1, color: '#3182CE' }
                    ])
                  }
                }
              },
              {
                name: '职务津贴',
                type: 'bar',
                stack: 'salary',
                data: [500, 800, 1200, 1800, 2500, 3000, 4000, 5000, 8000],
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#48BB78' },
                    { offset: 1, color: '#2F855A' }
                  ])
                },
                emphasis: {
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#68D391' },
                      { offset: 1, color: '#38A169' }
                    ])
                  }
                }
              },
              {
                name: '绩效奖金',
                type: 'bar',
                stack: 'salary',
                data: [300, 500, 800, 1200, 1800, 2500, 3500, 5000, 10000],
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#ED8936' },
                    { offset: 1, color: '#C05621' }
                  ])
                },
                emphasis: {
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#F6AD55' },
                      { offset: 1, color: '#DD6B20' }
                    ])
                  }
                }
              },
              {
                name: '总薪资',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 8,
                data: [3800, 5300, 7500, 10000, 13300, 17500, 22500, 30000, 48000],
                itemStyle: {
                  color: '#fff'
                },
                lineStyle: {
                  width: 3,
                  shadowColor: 'rgba(0,0,0,0.2)',
                  shadowBlur: 10
                },
                emphasis: {
                  itemStyle: {
                    borderWidth: 3,
                    borderColor: '#fff',
                    shadowColor: 'rgba(0,0,0,0.5)',
                    shadowBlur: 10
                  }
                },
                z: 2
              }
            ],
            animation: true,
            animationDuration: 1500,
            animationEasing: 'cubicInOut'
          }
          salaryChart.setOption(salaryOption)
        }

        // 等级分布图表
        const levelChartDom = document.getElementById('levelDistributionChart')
        if (levelChartDom && levelChartDom.offsetWidth > 0 && levelChartDom.offsetHeight > 0) {
          // 如果图表已存在，先销毁
          if (levelChart) {
            try {
              levelChart.dispose()
            } catch (e) {
              console.warn('销毁等级图表失败:', e)
            }
            levelChart = null
          }

          levelChart = echarts.init(levelChartDom)

          // 从 levels ref 中准备数据
          const pieData = levels.value
            .map((level) => ({
              value: level.currentCount,
              name: level.name
            }))
            .sort((a, b) => a.value - b.value)

          const levelOption = {
            title: {
              text: '各等级仙官人数分布',
              subtext: '南丁格尔玫瑰图',
              left: 'center',
              textStyle: {
                color: '#fff',
                fontSize: 18,
                fontWeight: 'bold'
              },
              subtextStyle: {
                color: 'rgba(255, 255, 255, 0.7)',
                fontSize: 12
              }
            },
            tooltip: {
              trigger: 'item',
              backgroundColor: 'rgba(0,0,0,0.8)',
              borderColor: 'rgba(255,255,255,0.2)',
              borderWidth: 1,
              textStyle: { color: '#fff' },
              formatter: '{a} <br/>{b} : {c}人 ({d}%)'
            },
            legend: {
              show: true,
              orient: 'vertical',
              right: 10,
              top: 'center',
              textStyle: { color: 'rgba(255, 255, 255, 0.85)' },
              data: pieData.map((p) => p.name)
            },
            series: [
              {
                name: '仙官人数',
                type: 'pie',
                radius: ['30%', '80%'],
                center: ['50%', '55%'],
                roseType: 'area', // Nightingale rose diagram
                itemStyle: {
                  borderRadius: 8,
                  borderColor: 'rgba(0,0,0,0.5)',
                  borderWidth: 2
                },
                label: {
                  show: false, // 标签太多会很乱，建议在 tooltip 中查看
                  position: 'outside'
                },
                emphasis: {
                  label: {
                    show: true
                  }
                },
                data: pieData
              }
            ]
          }
          levelChart.setOption(levelOption)
        }

        // 晋升趋势图表
        const trendChartDom = document.getElementById('promotionTrendChart')
        if (trendChartDom && trendChartDom.offsetWidth > 0 && trendChartDom.offsetHeight > 0) {
          // 如果图表已存在，先销毁
          if (trendChart) {
            try {
              trendChart.dispose()
            } catch (e) {
              console.warn('销毁趋势图表失败:', e)
            }
            trendChart = null
          }

          trendChart = echarts.init(trendChartDom)
          const trendOption = {
            color: ['#80FFA5', '#00DDFF', '#FFBF00'],
            title: {
              text: '近一年职位变动趋势',
              left: 'center',
              textStyle: {
                color: '#fff',
                fontSize: 18,
                fontWeight: 'bold'
              }
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              },
              backgroundColor: 'rgba(0,0,0,0.8)',
              borderColor: 'rgba(255,255,255,0.2)',
              borderWidth: 1,
              textStyle: { color: '#fff' }
            },
            legend: {
              data: ['晋升人数', '降职人数', '调岗人数'],
              top: 35,
              textStyle: { color: 'rgba(255, 255, 255, 0.85)' },
              icon: 'rect',
              itemWidth: 14,
              itemHeight: 5
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [
              {
                type: 'category',
                boundaryGap: false,
                data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                axisLine: {
                  lineStyle: {
                    color: 'rgba(255,255,255,0.3)'
                  }
                },
                axisLabel: {
                  color: 'rgba(255,255,255,0.7)'
                }
              }
            ],
            yAxis: [
              {
                type: 'value',
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: 'rgba(255,255,255,0.3)'
                  }
                },
                axisLabel: {
                  color: 'rgba(255,255,255,0.7)'
                },
                splitLine: {
                  lineStyle: {
                    color: 'rgba(255,255,255,0.1)',
                    type: 'dashed'
                  }
                }
              }
            ],
            series: [
              {
                name: '晋升人数',
                type: 'line',
                smooth: true,
                lineStyle: {
                  width: 2
                },
                showSymbol: false,
                areaStyle: {
                  opacity: 0.8,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: 'rgba(128, 255, 165, 0.5)'
                    },
                    {
                      offset: 1,
                      color: 'rgba(1, 191, 236, 0)'
                    }
                  ])
                },
                emphasis: {
                  focus: 'series'
                },
                data: [12, 8, 15, 10, 18, 22, 16, 14, 20, 25, 19, 23]
              },
              {
                name: '降职人数',
                type: 'line',
                smooth: true,
                lineStyle: {
                  width: 2
                },
                showSymbol: false,
                areaStyle: {
                  opacity: 0.8,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: 'rgba(255, 191, 0, 0.5)'
                    },
                    {
                      offset: 1,
                      color: 'rgba(255, 191, 0, 0)'
                    }
                  ])
                },
                emphasis: {
                  focus: 'series'
                },
                data: [3, 2, 4, 1, 2, 3, 1, 2, 1, 2, 1, 2] // 修正数据长度
              },
              {
                name: '调岗人数',
                type: 'line',
                smooth: true,
                lineStyle: {
                  width: 2
                },
                showSymbol: false,
                areaStyle: {
                  opacity: 0.8,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: 'rgba(0, 221, 255, 0.5)'
                    },
                    {
                      offset: 1,
                      color: 'rgba(0, 221, 255, 0)'
                    }
                  ])
                },
                emphasis: {
                  focus: 'series'
                },
                data: [5, 8, 6, 12, 9, 7, 11, 8, 10, 6, 9, 8]
              }
            ]
          }
          trendChart.setOption(trendOption)
        }

        console.log('图表初始化完成')
      } catch (error) {
        console.error('图表初始化失败:', error)
        message.error('图表初始化失败，请刷新页面重试')
      }
    })
  }, 300)
}

const resizeAllCharts = () => {
  setTimeout(() => {
    try {
      if (salaryChart && !salaryChart.isDisposed()) {
        salaryChart.resize()
      }
      if (levelChart && !levelChart.isDisposed()) {
        levelChart.resize()
      }
      if (trendChart && !trendChart.isDisposed()) {
        trendChart.resize()
      }
    } catch (error) {
      console.error('图表resize失败:', error)
    }
  }, 100)
}

onMounted(() => {
  window.addEventListener('resize', resizeAllCharts)
})

// 统一处理组件卸载时的资源清理
onUnmounted(() => {
  window.removeEventListener('resize', resizeAllCharts)

  try {
    if (salaryChart && !salaryChart.isDisposed()) {
      salaryChart.dispose()
      salaryChart = null
    }
    if (levelChart && !levelChart.isDisposed()) {
      levelChart.dispose()
      levelChart = null
    }
    if (trendChart && !trendChart.isDisposed()) {
      trendChart.dispose()
      trendChart = null
    }
  } catch (error) {
    console.error('图表销毁失败:', error)
  }
})
</script>

<style lang="scss" scoped>
.level-setting-container {
  padding: 24px;

  // 页面头部
  .level-header {
    text-align: center;
    margin-bottom: 32px;

    .header-content {
      .ancient-title {
        font-size: 32px;
        font-weight: bold;
        color: $secondary-color;
        margin-bottom: 8px;
        text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
      }

      .header-subtitle {
        font-size: 16px;
        color: $text-secondary;
        letter-spacing: 2px;
      }
    }

    .header-decoration {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 24px;
      gap: 16px;

      .decoration-line {
        width: 80px;
        height: 1px;
        background: linear-gradient(90deg, transparent, $secondary-color, transparent);
      }

      .decoration-symbol {
        font-size: 20px;
        color: $secondary-color;
        font-weight: bold;
      }
    }
  }

  // 路由信息
  .route-info {
    margin-bottom: 24px;
    padding: 12px 16px;
    border-radius: 8px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  // 选项卡区域
  .tabs-section {
    margin-bottom: 24px;

    :deep(.ant-tabs-card) {
      .ant-tabs-tab {
        border: 1px solid rgba(212, 153, 10, 0.2);
        background: rgba(212, 153, 10, 0.05);

        &.ant-tabs-tab-active {
          background: $secondary-color;
          color: white;
        }
      }
    }
  }

  // 操作区域
  .action-section {
    margin-bottom: 24px;

    .section-title {
      font-size: 20px;
      font-weight: bold;
      color: $primary-color;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 8px;

      .section-icon {
        color: $secondary-color;
      }
    }
  }

  // 等级列表区域
  .level-list-section {
    :deep(.ant-card) {
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 12px;
    }

    :deep(.ant-card-head) {
      border-bottom: 1px solid rgba(212, 153, 10, 0.2);
    }

    :deep(.ant-table) {
      .ant-table-thead > tr > th {
        background: rgba(212, 153, 10, 0.1);
      }
    }

    .salary-range {
      color: $secondary-color;
      font-weight: bold;
    }
  }

  // 晋升流程区域
  .promotion-section {
    .promotion-flow-chart {
      margin-bottom: 24px;

      .flow-steps {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 16px;

        .step-item {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 12px;

          .step-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: $secondary-color;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
          }

          .step-content {
            flex: 1;

            h5 {
              margin: 0 0 4px 0;
              color: $primary-color;
              font-weight: bold;
            }

            p {
              margin: 0 0 8px 0;
              color: $text-secondary;
              font-size: 12px;
            }
          }

          .step-arrow {
            margin: 0 16px;
            color: $secondary-color;
            font-size: 16px;
          }
        }
      }
    }

    .promotion-stats {
      .stats-cards {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;

        .stat-card {
          padding: 16px;
          border: 1px solid rgba(212, 153, 10, 0.2);
          border-radius: 8px;
          text-align: center;

          .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: $secondary-color;
          }

          .stat-label {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }
    }

    .promotion-rules {
      margin-top: 24px;

      .rules-list {
        .rule-item {
          margin-bottom: 12px;
          padding: 12px;
          border: 1px solid rgba(212, 153, 10, 0.2);
          border-radius: 8px;

          .rule-title {
            font-weight: bold;
            color: $primary-color;
            margin-bottom: 4px;
          }

          .rule-content {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }
    }
  }

  // 薪资体系区域
  .salary-section {
    .salary-chart {
      margin-bottom: 24px;

      .chart-container {
        width: 100%;
        height: 500px;
      }
    }

    .salary-table {
      .salary-amount {
        color: $secondary-color;
        font-weight: bold;
      }

      .salary-total {
        color: $primary-color;
        font-weight: bold;
        font-size: 16px;
      }
    }

    .salary-calculator {
      .salary-result {
        margin-top: 16px;
        padding: 16px;
        border: 1px solid rgba(212, 153, 10, 0.2);
        border-radius: 8px;

        .result-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .amount {
            color: $secondary-color;
            font-weight: bold;
          }
        }

        .result-total {
          display: flex;
          justify-content: space-between;
          padding-top: 8px;
          border-top: 1px solid rgba(212, 153, 10, 0.2);
          font-weight: bold;

          .total-amount {
            color: $primary-color;
            font-size: 16px;
          }
        }
      }
    }
  }

  // 考核标准区域
  .assessment-section {
    .assessment-config {
      margin-bottom: 24px;
    }

    .assessment-template {
      .template-list {
        .template-item {
          margin-bottom: 12px;
          padding: 12px;
          border: 1px solid rgba(212, 153, 10, 0.2);
          border-radius: 8px;

          .template-name {
            font-weight: bold;
            color: $primary-color;
            margin-bottom: 4px;
          }

          .template-description {
            font-size: 12px;
            color: $text-secondary;
            margin-bottom: 8px;
          }

          .template-actions {
            text-align: right;
          }
        }
      }
    }
  }

  // 统计分析区域
  .statistics-section {
    .level-distribution,
    .promotion-trend {
      .distribution-chart,
      .trend-chart {
        height: 300px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid rgba(212, 153, 10, 0.2);
        border-radius: 8px;
        color: $text-secondary;
      }
    }

    .department-stats {
      .stats-list {
        .dept-stat-item {
          margin-bottom: 16px;
          padding: 12px;
          border: 1px solid rgba(212, 153, 10, 0.2);
          border-radius: 8px;

          .dept-name {
            font-weight: bold;
            color: $primary-color;
            margin-bottom: 8px;
          }

          .dept-levels {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
          }
        }
      }
    }

    .performance-stats,
    .retention-stats {
      .performance-list,
      .retention-list {
        .perf-item,
        .retention-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 12px;
          padding: 8px;
          border: 1px solid rgba(212, 153, 10, 0.2);
          border-radius: 4px;

          .perf-level,
          .retention-level {
            font-weight: bold;
            color: $primary-color;
          }

          .perf-score,
          .retention-rate {
            flex: 1;
            margin-left: 16px;
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }

  // 导入区域
  .import-template {
    margin-top: 16px;
    text-align: center;
  }
}
</style>
